package cliqueproblem;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import java.util.HashMap;

import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;

public class DotImport {
	private UndirectedGraph<Vertex, DefaultEdge> inputGraph;
	private HashMap<String, Vertex> vertexMap;
	private boolean correctData;
	private String path;

	public DotImport(String p) {
		path = p;
		if (!path.endsWith(".dot")) {
			System.out.println("File must be .dot");
			correctData = false;
		} else {
			if (new File(path).exists()) {
				inputGraph = new SimpleGraph<Vertex, DefaultEdge>(DefaultEdge.class);
				vertexMap = new HashMap<String, Vertex>();
				correctData = true;
			} else {
				System.out.println("File " + path + " does not exist.");
				correctData = false;
			}
		}
	}

	public void importGraph() {
		if (correctData) {
			try {
				System.out.println("Reading file " + path);

				BufferedReader bufReader = new BufferedReader(new FileReader(path));
				String row = bufReader.readLine();
				row = bufReader.readLine();

				while (row != null) {
					String[] splitRow = row.split("--");

					// new edge
					if (splitRow.length > 1) {
						Vertex begin = getVertex(splitRow[0].trim());
						Vertex end = getVertex(splitRow[1].trim().replaceFirst(";", ""));

						if (begin == end) {
							System.out.println("Loops not allowed:" + row);
						} else {
							inputGraph.addEdge(begin, end);
						}
					}
					// new vertex
					else if (!row.trim().isEmpty() && !splitRow[0].trim().equals("}")) {
						String vertexName = splitRow[0].trim().replaceFirst(";", "");
						vertexMap.put(vertexName, getVertex(vertexName));
					}
					row = bufReader.readLine();
				}
				bufReader.close();
			} catch (IOException e) {
				System.out.println("Can not read file.");
				correctData = false;
				e.printStackTrace();
			}
		}
	}

	// returns vertex from vertexMap
	// creates vertex(if not exists)
	private Vertex getVertex(String s) {
		if (vertexMap.containsKey(s)) {
			return vertexMap.get(s);
		} else {
			Vertex v = new Vertex(s);
			inputGraph.addVertex(v);
			vertexMap.put(s, v);
			return v;
		}
	}

	public UndirectedGraph<Vertex, DefaultEdge> getGraph() {
		return inputGraph;
	}

	public boolean isCorrect() {
		return correctData;
	}
}
